package com.levy.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;

/**
 * Created by levy on 2019/7/3.
 */
public class Base64Utils {

    /**
     * 将文件转成base64 字符串
     * @param
     * @return  *
     * @throws Exception
     */

    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        String encode = new BASE64Encoder().encode(buffer);
        return encode.replaceAll("\r|\n","");

    }

    /**
     * 将base64字符解码保存文件
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */

    public static void decoderBase64File(String base64Code, String targetPath)
            throws Exception {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();

    }


    /**
     * 将base64字符解码
     * @param base64Code
     * @throws Exception
     */

    public static String decoderBase64Str(String base64Code)
            throws Exception {
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        return  new String(buffer);
    }

}
